# coding = utf-8
import datetime
import json
import logging
import os
import random
import string
import time
from io import BytesIO

from PIL import Image
from django.db.models import Q
from django.http import HttpResponse
from lawoffice import settings
from rest_framework import mixins, status
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet, GenericViewSet, ModelViewSet
from wxchat.api.permissions import WeixinPermission
from wxchat.api.serializers import SwipeImageSerializer, UserRoleSerializer, WxUserInfoSerializer, MemberRoleSerializer
from wxchat.models import SwipeImage, WxUserInfo, MemberRole
from wxchat.utils import create_qrcode, mergeRightImage, mergeImage
from wxchat.views import wxClient


logger = logging.getLogger("django")


class QrCodeAPIView(APIView):
    """二维码"""
    authentication_classes = ()

    def get(self, request, *args, **kwargs):
        direct_url = request.query_params.get("url")
        f = BytesIO()
        if direct_url:
            image = create_qrcode(direct_url)
            image.save(f, "PNG")

        return HttpResponse(f.getvalue(), content_type="image/png")


class QrCodeWithLogoAPIView(APIView):
    """二维码带Logo"""
    authentication_classes = ()

    def get(self, request, *args, **kwargs):
        direct_url = request.query_params.get("url")
        f = BytesIO()
        if direct_url:
            image = create_qrcode(direct_url)
            logo = Image.open(os.path.join(settings.STATIC_ROOT, 'images/logo.jpg'))
            image = mergeImage(image, logo)
            image.save(f, "PNG")

        return HttpResponse(f.getvalue(), content_type="image/png")


class QrCodeWithBgAPIView(APIView):
    """二维码"""
    authentication_classes = ()

    def get(self, request, *args, **kwargs):
        direct_url = request.query_params.get("url")
        code = request.query_params.get("code")
        f = BytesIO()
        if direct_url:
            image = create_qrcode(direct_url)
            bg_image_path = ''
            if code == "consult":
                bg_image_path = os.path.join(settings.STATIC_ROOT, r'images/card-bg.png')
            elif code == "advisor":
                bg_image_path = os.path.join(settings.STATIC_ROOT, r'images/advisor.png')
            elif code == "lawyer":
                bg_image_path = os.path.join(settings.STATIC_ROOT, r'images/lawyer.png')
            elif code == "rights":
                bg_image_path = os.path.join(settings.STATIC_ROOT, r'images/rights.png')

            bg = Image.open(bg_image_path)
            image = mergeRightImage(bg, image)
            image.save(f, "PNG")
        return HttpResponse(f.getvalue(), content_type="image/png")


class SwipeImageViewSet(ReadOnlyModelViewSet):
    """图片轮播"""
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = SwipeImage.objects.filter(is_show=True)
    serializer_class = SwipeImageSerializer


class UserRoleViewSet(mixins.RetrieveModelMixin,
                      mixins.UpdateModelMixin,
                      GenericViewSet):
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = WxUserInfo.objects.all()
    serializer_class = UserRoleSerializer
    lookup_field = 'openid'
    lookup_url_kwarg = 'openid'


class WxUserInfoViewSet(ModelViewSet):
    """用户信息(公众号号)"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = WxUserInfo.objects.all()
    serializer_class = WxUserInfoSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name) | Q(nickname__contains=name) | Q(telephone__contains=name))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class MemberRoleViewSet(ModelViewSet):
    """用户角色"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = MemberRole.objects.all()
    serializer_class = MemberRoleSerializer


class WxMenuAPIView(APIView):
    authentication_classes = ()
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        res = self.get_menu()
        return Response(res)

    def post(self, request, *args, **kwargs):
        flag = request.data.get("flag", None)

        res = None
        if flag == "create":
            res = self.create_menu()
        elif flag == "delete":
            res = self.delete_menu()
        print(res)
        return Response(res)

    def create_menu(self):
        client = wxClient()
        resp = client.menu.create({
            "button": [
                {
                    "type": "view",
                    "name": "律师服务",
                    "url": settings.ROOT_URL + "/"
                },
                # {
                #     "type": "view",
                #     "name": "我的案件",
                #     "url": settings.ROOT_URL + "/#mycase"
                # },

            ]
        })
        return resp

    def delete_menu(self):
        client = wxClient()
        resp = client.menu.delete()
        return resp

    def get_menu(self):
        client = wxClient()
        resp = client.menu.get()
        return resp


class WxSwipeImageViewSet(ModelViewSet):
    """图片轮播维护"""
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = SwipeImage.objects.all()
    serializer_class = SwipeImageSerializer


class SwipeImageUploadAPIView(APIView):

    def post(self, request, *args, **kwargs):
        # 接收文件
        sid = request.data.get("id", None)
        image = request.FILES.get('image', None)
        name = request.data.get("name", "")
        path = request.data.get("path", "")
        sort = request.data.get("sort", 0)
        is_show = request.data.get("is_show", None)
        print(sid, type(sid), path, sort, is_show)
        if image:
            upload_path = SwipeImage.image.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            file_info = image.name.split(".")
            old_file_name = file_info[0]
            file_suffix = file_info[1]
            file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
            file_path = os.path.join(dirs, file_name)

            with open(file_path, 'wb') as f:
                for chunk in image.chunks():
                    f.write(chunk)

            file_url = '{0}{1}'.format(upload_path, file_name)
            data = {
                'name': name,
                'path': path,
                'image': file_url,
                'sort': int(sort),
                'is_show': 1 if is_show == "true" else 0,
            }

            if sid:
                SwipeImage.objects.filter(id=int(sid)).update(**data)
                obj = SwipeImage.objects.filter(id=int(sid)).first()
            else:
                obj = SwipeImage.objects.create(**data)

            dict_obj = {
                "id": obj.id,
                "name": obj.name,
                "path": obj.path,
                "sort": obj.sort,
                "is_show": obj.is_show,
                "image": "{}://{}{}".format(request.scheme, request.get_host(), obj.image.url),
            }

            msg = {
                "status_code": status.HTTP_200_OK,
                "image": dict_obj,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


# 获取用户openid列表
def get_user_info(request):
    client = wxClient()
    userid_list = client.user.get_followers()
    logger.info(userid_list)
    WxUserInfo.objects.all().update(qr_scene=0)

    if 'errcode' not in userid_list and userid_list['count'] > 0:
        openid_list = userid_list['data']['openid']
        n = 100
        for openids in [openid_list[i:i + n] for i in range(0, len(openid_list), n)]:
            print("openids:", openids)
            userinfo_lists = client.user.get_batch(openids)
            for user in userinfo_lists:
                logger.info(user)
                sub_time = user.pop('subscribe_time')
                sub_time = datetime.datetime.fromtimestamp(sub_time).strftime('%Y-%m-%d %H:%M:%S')
                user['subscribe_time'] = sub_time
                WxUserInfo.objects.update_or_create(defaults=user, openid=user['openid'])

    return Response(userid_list)


class UserLoginQrCode(APIView):
    """显示扫码登录二维码"""
    authentication_classes = ()
    permission_classes = ()

    def post(self, request, *args, **kwargs):
        client = wxClient()
        room = "".join(random.choice(string.ascii_letters) for i in range(12))
        res = client.qrcode.create({
            'expire_seconds': 3600,
            'action_name': 'QR_STR_SCENE',
            'action_info': {
                'scene': {'scene_str': room},
            }
        })

        if 'errcode' in res and res['errmsg']:
            return Response(res)

        ticket = res["ticket"]

        img_url = client.qrcode.get_url(ticket)

        return Response({"image_url": img_url, "room": room})


class VideoLoginUserInfo(APIView):
    """视频用户登录信息"""
    authentication_classes = ()

    def get(self, request, *args, **kwargs):

        room = request.query_params.get("room")
        data = {
            "status_code": -1,
            "error_msg": "查无此人"
        }
        if room:
            login_user = WxUserInfo.objects.filter(qr_scene_str=room).first()
            if login_user:
                data["status_code"] = 0
                data["error_msg"] = ""
                data["data"] = WxUserInfoSerializer(login_user).data

        return Response(data)
